package com.bjbn.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjbn.bean.IacUser;
import com.bjbn.entity.DataSyncLog;
import com.bjbn.entity.Position;
import com.bjbn.entity.User;
import com.bjbn.entity.UserRelation;
import com.bjbn.mapper.DataSyncLogMapper;
import com.bjbn.mapper.UserMapper;
import com.bjbn.mapper.UserRelationMapper;
import com.bjbn.service.IacUserService;
import com.bjbn.service.KafkaProducerService;
import com.bjbn.service.PositionService;
import com.bjbn.util.SSLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
public class IacUserServiceImpl implements IacUserService {

    @Autowired
    private PositionService positionService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRelationMapper userRelationMapper;

    @Autowired
    private DataSyncLogMapper dataSyncLogMapper;

    @Autowired
    private KafkaProducerService kafkaProducerService;

    @Value("${gdairport-sso-url}")
    private String gdairportSsoUrl;

    @Override
    public List<IacUser> getAllIacUser(String modifiedDate, Integer pageNumber, Integer pageSize) {
        LocalDateTime now = LocalDateTime.now().minusMinutes(5);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化时间
        String todayZeroTime = now.format(formatter);
        if (modifiedDate != null) {
            todayZeroTime = modifiedDate;
        }
        //todayZeroTime = "2025-04-10 00:00:00";
        String url = gdairportSsoUrl + "maxkey-mgt-api/api/idm/Users/.search?r=1&pageNumber=" + pageNumber + "&pageSize=" + pageSize;
        url = url + "&modifiedDate=" + todayZeroTime;
        HttpRequest request = HttpUtil
                .createGet(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", "Basic MTEwOTE1OTkyNDE2NTc3MTI2NDp5RkIzTVRRd05ESXdNalV4TkRBMk16ZzNORGN6Vlg=")
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory());

        HttpResponse response0 = request.execute();

        if (response0.getStatus() == 200) {
            JSONObject res = JSONObject.parseObject(response0.body());
            if (res.getInteger("code") == 0) {
                JSONObject data = res.getJSONObject("data");
                JSONArray rows = data.getJSONArray("rows");
                return rows.toJavaList(IacUser.class);
            }
        }

        return null;
    }

    @Override
    public void updateIacUserAll(String modifiedDate) {
        List<IacUser> iacUsers = getAllIacUser(modifiedDate, 1, 4000);
        updateIacUser(iacUsers);
    }

    @Override
    public void updateIacUser(List<IacUser> iacUsers) {
        // 将数据推送到kafka队列
        kafkaProducerService.sendBatchMessages("IAC_USER_UPDATE_DATA_OUT", iacUsers);

        for (IacUser iacUser : iacUsers) {
            // 岗位信息是否存在
            if (iacUser.getJobTitle() != null) {
                // 根据岗位名称和部门名称查询岗位信息，如果不存在则创建该岗位
                Position position = positionService.getPositionByNameAndOrganization(iacUser.getJobTitle(), iacUser.getDepartment());
                if (position == null) {
                    position = new Position();
                    position.setFullName(iacUser.getJobTitle());
                    position.setOrganizeId(iacUser.getDepartmentId());
                    position.setType(1);
                    position.setEnabledMark(1);
                    position.setCreatorTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                    position.setCreatorUserId("349057407209541");
                    position.setTenantId("0");
                    String id = IdUtil.randomUUID().toUpperCase();
                    position.setId(id);

                    positionService.insertPosition(position);
                }

                User user = new User();
                user.setId(iacUser.getId());
                user.setAccount(iacUser.getUsername());
                user.setRealName(iacUser.getDisplayName());
                user.setHeadIcon(iacUser.getPictureBase64() != null ? iacUser.getPictureBase64() : "001.png");
                // 快开平台 0保密 1男 2女，身份认证中心0未知 1女性 2男性
                String gender = "0";
                if ("1".equals(iacUser.getGender())) {
                    gender = "2";
                } else if ("2".equals(iacUser.getGender())) {
                    gender = "1";
                }
                user.setGender(gender);
                user.setMobilePhone(iacUser.getMobile());
                user.setTelePhone(iacUser.getMobile());
                user.setEmail(iacUser.getEmail());
                // 同步用户使用默认密码，更新时不能覆盖密码
                user.setPassword("22292382eb48e5abc85712cd5721273a");
                user.setSecretkey("675714949024058373");
                user.setIsAdministrator(0);
                user.setOrganizeId(iacUser.getDepartmentId());
                user.setPositionId(position.getId());
                user.setEnabledMark("1".equals(iacUser.getStatus()) ? 1 : 0);
                user.setSortCode(1);
                user.setCreatorTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                user.setCreatorUserId("349057407209541");
                user.setLastModifyTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                user.setLastModifyUserId("349057407209541");
                user.setTenantId("0");
                user.setRank(iacUser.getJobLevel());
                // 普通用户
                user.setStanding(3);
                user.setAppStanding(3);

                // 保存用户信息，存在则更新，不存在则创建
                userMapper.insertOrUpdate(user);
                // 用户和组织对应关系，如果存在则更新，如果不存在则创建
                UserRelation userRelation = new UserRelation();
                userRelation.setId(iacUser.getId());
                userRelation.setUserId(iacUser.getId());
                userRelation.setObjectType("Organize");
                userRelation.setObjectId(iacUser.getDepartmentId());
                userRelation.setCreatorTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                userRelation.setCreatorUserId("349057407209541");
                userRelation.setLastModifyTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                userRelation.setLastModifyUserId("349057407209541");
                userRelation.setTenantId("0");
                userRelationMapper.insertOrUpdate(userRelation);
                User old = userMapper.selectById(iacUser.getId());
                DataSyncLog dataSyncLog = new DataSyncLog();
                dataSyncLog.setBeforeChange(JSONObject.toJSONString(old));
                dataSyncLog.setAfterChange(JSONObject.toJSONString(user));
                dataSyncLog.setType("user");
                dataSyncLog.setCreateTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
                dataSyncLogMapper.insert(dataSyncLog);
            }
        }
    }


}
